package cn.hmcode.device.mqtt;

import cn.hmcode.device.constance.MqttConstants;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class MqttConsumer implements MqttCallbackExtended {


    private MqttClient mqttClient;

    /**
     * 没有在容器中的 MqttConsumer 想使用 容器中 MqttClient
     * 可以在创建 MqttConsumer 的时候，把 MqttClient 通过构造方法 传入进来
     * @param mqttClient
     */
    public MqttConsumer(MqttClient mqttClient) {
        this.mqttClient = mqttClient;
    }

    @Override
    public void connectComplete(boolean b, String s) {
        log.debug("connectComplete 连接成功");
        //在和EMQX连接成功后
        //订阅Topic 设备返回的开始充电结果Topic
        String topicChargingResult = MqttConstants.TOPIC_CHARGING_RESULT;
        try {
            log.debug("订单服务订阅设备返回的开始充电结果Topic:{}", topicChargingResult);
            mqttClient.subscribe(topicChargingResult);
            log.debug("订单服务订阅设备返回的开始充电结果Topic:{},成功", topicChargingResult);
        } catch (MqttException e) {
            //打印异常信息 可能进行重试，接入告警系统 告警
            throw new RuntimeException(e);
        }
    }

    @Override
    public void connectionLost(Throwable throwable) {

    }

    @Override
    public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
        log.debug("接收到消息"+new String(mqttMessage.getPayload()));
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.debug("断开连接");
    }
}
